/*
 * Copyright (C) 2020 Baidu, Inc. All Rights Reserved.
 */
package completableFuture;

import org.springframework.util.StopWatch;
import sun.awt.dnd.SunDragSourceContextPeer;

import java.util.concurrent.*;

/**
 * @Author wangtengyu
 * @Date 2020/8/24 11:06 上午
 * @Description  测试一下completeable方法
 */
public class CompletableDemo {


    static {
        cachePool= Executors.newCachedThreadPool();
    }

    public static ExecutorService cachePool;

    public static void main(String args[]){
        testComplete();
//        testFuture();
    }

    /**
     * 测试completeableFuture的complete方法，complete
     * 让whencompleteAble的方法能够执行，不用学future那样去做轮询了
     */
    private static void testComplete(){
        CompletableFuture<String> completableFuture=new CompletableFuture<>();
        cachePool.execute(()->{
            try {
                System.out.println("异步任务开始执行");
                TimeUnit.SECONDS.sleep(3);
                completableFuture.complete("异步任务执行结果");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("不进行阻塞");

        CompletableFuture<String> completableFuture2Two=completableFuture.whenComplete((s,Throwable)->{
            System.out.println("异步任务执行完毕了"+s);
        });


    }

    /**
     * 测试future版本的
     */
    private static void testFuture()  {
        Future<String> future=cachePool.submit(()->{
            System.out.println("异步任务开始执行");
            TimeUnit.SECONDS.sleep(3);
            return "异步任务执行结果";
        });

        System.out.println("做一些其他事");

        StopWatch stopWatch=new StopWatch("test");
        stopWatch.start("task1");
        long count=0;
        while (true){
            count++;
            if (future.isDone()){
                break;
            }
        }
        stopWatch.stop();
        System.out.println("获取异步任务轮询耗时"+stopWatch.prettyPrint());
        System.out.println(stopWatch.getTotalTimeSeconds());
        System.out.println("获取异步任务轮询次数"+count);

        String result= null;
        try {
            result = future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("获取future数据"+result);


    }
}
